package smap;

import javax.swing.JOptionPane;

import BD.CursoBD;
import DAO.CursoDAO;

public class TelaCadCurso extends javax.swing.JDialog {
    
    CursoBD cur = new CursoBD();
    CursoDAO curDao = new CursoDAO();
    
    private boolean cadastrar; //true para cadastrar, false para alterar
    
    public boolean isCadastrar() {
        return cadastrar;
    }

    public void setCadastrar(boolean cadastrar) {
        this.cadastrar = cadastrar;
    }
    
    public TelaCadCurso(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        lblNome = new javax.swing.JLabel();
        lblTipoCurso = new javax.swing.JLabel();
        lblProfessor = new javax.swing.JLabel();
        lblCodigo = new javax.swing.JLabel();
        txtCodigo = new javax.swing.JTextField();
        txtNome = new javax.swing.JTextField();
        lblAnoInicio = new javax.swing.JLabel();
        cmbTipoCurso = new javax.swing.JComboBox();
        txtDuracao = new javax.swing.JFormattedTextField();
        jycAno = new com.toedter.calendar.JYearChooser();
        lblCreditos = new javax.swing.JLabel();
        txtCreditos = new javax.swing.JFormattedTextField();
        jLabel1 = new javax.swing.JLabel();
        txtTempoCredito = new javax.swing.JFormattedTextField();
        pnlVoltar1 = new javax.swing.JPanel();
        btnVoltar1 = new javax.swing.JButton();
        btnCadastrar = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Cadastrar Curso");
        setResizable(false);

        jPanel1.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(192, 192, 192)));

        lblNome.setText("* Nome:");

        lblTipoCurso.setText("Tipo Curso:");

        lblProfessor.setText("* Duração(anos):");

        lblCodigo.setText("* Código:");

        txtCodigo.setEnabled(false);

        lblAnoInicio.setText("Ano Inicio:");

        cmbTipoCurso.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Mestrado", "Doutorado" }));

        try {
            txtDuracao.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("#")));
        } catch (java.text.ParseException ex) {
            ex.printStackTrace();
        }

        lblCreditos.setText("* Créditos:");

        txtCreditos.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.NumberFormatter(new java.text.DecimalFormat("#0"))));

        jLabel1.setText("* Tempo para completar créditos (anos):");

        try {
            txtTempoCredito.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("#")));
        } catch (java.text.ParseException ex) {
            ex.printStackTrace();
        }

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(lblProfessor)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(txtDuracao))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(lblTipoCurso)
                            .addComponent(lblAnoInicio))
                        .addGap(3, 3, 3)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(cmbTipoCurso, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addComponent(jycAno, javax.swing.GroupLayout.PREFERRED_SIZE, 89, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(0, 0, Short.MAX_VALUE))))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(lblNome)
                            .addComponent(lblCodigo))
                        .addGap(18, 18, 18)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(txtCodigo)
                            .addComponent(txtNome)))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(lblCreditos)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(txtCreditos))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(txtTempoCredito, javax.swing.GroupLayout.DEFAULT_SIZE, 75, Short.MAX_VALUE)))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(17, 17, 17)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblCodigo)
                    .addComponent(txtCodigo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(15, 15, 15)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblNome)
                    .addComponent(txtNome, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblTipoCurso)
                    .addComponent(cmbTipoCurso, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(lblAnoInicio)
                    .addComponent(jycAno, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblProfessor)
                    .addComponent(txtDuracao, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblCreditos)
                    .addComponent(txtCreditos, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(txtTempoCredito, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pnlVoltar1.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(192, 192, 192)));

        btnVoltar1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Imagens/voltar-icon.png"))); // NOI18N
        btnVoltar1.setText("Voltar");
        btnVoltar1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnVoltar1ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout pnlVoltar1Layout = new javax.swing.GroupLayout(pnlVoltar1);
        pnlVoltar1.setLayout(pnlVoltar1Layout);
        pnlVoltar1Layout.setHorizontalGroup(
            pnlVoltar1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, pnlVoltar1Layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(btnVoltar1, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(98, 98, 98))
        );
        pnlVoltar1Layout.setVerticalGroup(
            pnlVoltar1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(pnlVoltar1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(btnVoltar1, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        btnCadastrar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Imagens/add-icon.png"))); // NOI18N
        btnCadastrar.setText("Cadastrar");
        btnCadastrar.setPreferredSize(new java.awt.Dimension(61, 23));
        btnCadastrar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCadastrarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(pnlVoltar1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(btnCadastrar, javax.swing.GroupLayout.PREFERRED_SIZE, 110, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(87, 87, 87))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(btnCadastrar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(pnlVoltar1, javax.swing.GroupLayout.PREFERRED_SIZE, 42, javax.swing.GroupLayout.PREFERRED_SIZE))
        );

        pack();
        java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
        java.awt.Dimension dialogSize = getSize();
        setLocation((screenSize.width-dialogSize.width)/2,(screenSize.height-dialogSize.height)/2);
    }// </editor-fold>//GEN-END:initComponents

    private void btnVoltar1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnVoltar1ActionPerformed
        this.dispose(); // Fecha Tela de Cadastro de Disciplina
    }//GEN-LAST:event_btnVoltar1ActionPerformed

    private void btnCadastrarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCadastrarActionPerformed
        if(txtCreditos.getText().length() > 5){
             JOptionPane.showMessageDialog(null,"Número de créditos muito alto.",
                    "Campos obrigatórios", JOptionPane.INFORMATION_MESSAGE);
        }
        else
        {
            if(txtNome.getText().trim().length() == 0 || txtDuracao.getText().trim().length() == 0
                 || txtCreditos.getText().trim().length() == 0 || txtTempoCredito.getText().trim().length() == 0
                 || Integer.parseInt(txtTempoCredito.getText()) < 0 || Integer.parseInt(txtCreditos.getText()) < 0)
            {
                
                if(txtTempoCredito.getText().trim().length() != 0){
                    if(Integer.parseInt(txtTempoCredito.getText()) < 0)
                    {
                        txtTempoCredito.setText("");
                    }
                }
                
                if(txtCreditos.getText().trim().length() != 0){
                    if(Integer.parseInt(txtCreditos.getText()) < 0)
                    {
                        txtCreditos.setText("");
                    }
                }
                
                 JOptionPane.showMessageDialog(null,"Campos nome, duração, créditos e tempo para completar créditos são obrigatórios",
                        "Campos obrigatórios", JOptionPane.INFORMATION_MESSAGE);
            }     
            else
            {
                if(Integer.parseInt(txtTempoCredito.getText()) >= Integer.parseInt(txtDuracao.getText())){
                    JOptionPane.showMessageDialog(null,"O tempo para concluir os créditos não pode ser maior ou igual ao o tempo do curso!", 
                         "Campos Obrigatórios", JOptionPane.INFORMATION_MESSAGE);
                }
                else{
                     //seta os dados do curso 
                     cur.setCodigo(Integer.parseInt(txtCodigo.getText()));
                     cur.setNome(txtNome.getText().trim());
                     cur.setTipoCurso(cmbTipoCurso.getSelectedItem().toString());
                     cur.setAnoInicio(jycAno.getValue());
                     cur.setDuracao(Integer.parseInt(txtDuracao.getText()));
                     cur.setCredito(Integer.parseInt(txtCreditos.getText()));
                     cur.setTempoCredito(Integer.parseInt(txtTempoCredito.getText()));

                     if(isCadastrar()){ //cadastrar
                         if(curDao.inserirCurso(cur)){
                             // Auto Incremento
                             autoIncremento();

                             //limpar campos
                             txtNome.setText("");
                             cmbTipoCurso.setSelectedIndex(0);
                             txtDuracao.setText("");
                             txtCreditos.setText("");
                             txtTempoCredito.setText("");
                         }
                     }
                     else{ //alterar
                         if(curDao.alterarCurso(cur)){
                             this.dispose();
                         }
                     }
                }
            }
        }
    }//GEN-LAST:event_btnCadastrarActionPerformed

    // Método para alterar os dados do Curso
    public void recebeObjejo (CursoBD cr){
        txtCodigo.setText(String.valueOf(cr.getCodigo()));
        txtNome.setText(cr.getNome());
        cmbTipoCurso.setSelectedItem(cr.getTipoCurso());        
        jycAno.setValue(cr.getAnoInicio());
        txtDuracao.setText(String.valueOf(cr.getDuracao())); 
        txtCreditos.setText(String.valueOf(cr.getCredito()));
        txtTempoCredito.setText(String.valueOf(cr.getTempoCredito()));
    }
    
    //Método para visualizar os dados do curso
    public void visualizarObjeto (CursoBD cr){
        recebeObjejo(cr);
        //Bloqueia os botões
        jycAno.setEnabled(false);
        txtCodigo.setEnabled(false);
        txtDuracao.setEnabled(false);
        txtNome.setEnabled(false);
        txtCreditos.setEnabled(false);
        cmbTipoCurso.setEnabled(false);
        btnCadastrar.setEnabled(false);
        txtTempoCredito.setEnabled(false);
    }
    
    public void autoIncremento(){
        txtCodigo.setText(String.valueOf(curDao.autoIncremento()));
    }
    
    public static void main(String args[]) {

        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /*
         * If Nimbus (introduced in Java SE 6) is not available, stay with the
         * default look and feel. For details see
         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(TelaCadCurso.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(TelaCadCurso.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(TelaCadCurso.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(TelaCadCurso.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>


        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                TelaCadCurso dialog = new TelaCadCurso(new javax.swing.JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {

                    @Override
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnCadastrar;
    private javax.swing.JButton btnVoltar1;
    private javax.swing.JComboBox cmbTipoCurso;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JPanel jPanel1;
    private com.toedter.calendar.JYearChooser jycAno;
    private javax.swing.JLabel lblAnoInicio;
    private javax.swing.JLabel lblCodigo;
    private javax.swing.JLabel lblCreditos;
    private javax.swing.JLabel lblNome;
    private javax.swing.JLabel lblProfessor;
    private javax.swing.JLabel lblTipoCurso;
    private javax.swing.JPanel pnlVoltar1;
    private javax.swing.JTextField txtCodigo;
    private javax.swing.JFormattedTextField txtCreditos;
    private javax.swing.JFormattedTextField txtDuracao;
    private javax.swing.JTextField txtNome;
    private javax.swing.JFormattedTextField txtTempoCredito;
    // End of variables declaration//GEN-END:variables
}
